package com.foriseland.social.socialRong.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ConfigFactory {

	private Properties properties;

	private String configFileName;
	
	protected Logger logger = LoggerFactory.getLogger(getClass());

	public void load(){
		properties=new Properties();
		
		InputStream inputStream=ConfigFactory.class.getResourceAsStream("/config.properties");
		
		if(inputStream==null){
			logger.error("inputStream is null");
		}else{
			try {
				properties.load(inputStream);
				logger.debug("loaded properties from resource " + configFileName +	": " +	properties);
			} catch (Exception e) {
				logger.error("problem loading properties from " + configFileName);
			} finally {
				try {
					inputStream.close();
				} catch (IOException ioe) {
					logger.error("could not close stream on " + configFileName, ioe);
				}
			}
		}
	}
	public static final String[] TRUE_VALUES = {"true", "1", "y", "yes"};
	public static final String[] FALSE_VALUES = {"false", "0", "n", "no"};
	public boolean getBoolean(String key) {
		return getBoolean(key, false);
	}

	public boolean getBoolean(String key, boolean defaultValue) {

		String s = properties.getProperty(key);

		if (s == null) return defaultValue;
		for (int i = 0; i < ConfigFactory.TRUE_VALUES.length; i++) {
			if (s.equalsIgnoreCase(ConfigFactory.TRUE_VALUES[i])) return true;
		}
		for (int i = 0; i < ConfigFactory.FALSE_VALUES.length; i++) {
			if (s.equalsIgnoreCase(ConfigFactory.FALSE_VALUES[i])) return false;
		}
		return defaultValue;
	}
	
	public String getString(String key) {
		return getString(key, "");
	}

	public String getString(String key, String defaultValue) {
		String s = properties.getProperty(key);
		return (s == null) ? defaultValue : s;
	}
	
	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void setConfigFileName(String configFileName) {
		this.configFileName = configFileName;
	}

	public int getInt(String key) {
		return getInt(key, 0);
	}

	public int getInt(String key, int defaultValue) {

		String s = properties.getProperty(key);

		if (s == null) return defaultValue;
		try {
			return Integer.parseInt(s);
		} catch (Exception e) {
			return defaultValue;
		}
	}
}
